package com.mobi.Survey.lib.model;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

import com.mobi.Survey.lib.db.AlarmTable;
import com.mobi.Survey.lib.utils.Helper;

public class AlarmPojo extends Pojo implements Parcelable {
	private long id;

	private long surveyId;
	private String surveyKey;
	private long start;
	private long end;
	private boolean active;
	private long sequanceNo;
	private String message;
	private String imageUrl;
	private String audioUrl;
	private String upperLimit;
	private String lowerLimit;
	private String buttons;
	private int pendingIntentId;
	private int repeatType;
	private boolean repeat;
	private long triggerTime;
	private boolean withRespectToCurrentTime;
	private String startTimeStr = "";
	private long installTime;

	private List<AlarmRepeatPojo> repeats = new ArrayList<AlarmRepeatPojo>();

	public AlarmPojo() {

	}

	DateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

	public AlarmPojo(SurveyDetailPojo surveyDetail) {

		this.setSurveyId(surveyDetail.getSurveyId());
		this.setSequanceNo(surveyDetail.getSequanceNo());

		String urls = surveyDetail.getControlParameter2();

		if (null != urls) {
			String[] urlTokens = urls.split("\\|");

			for (String urlToken : urlTokens) {

				String url[] = urlToken.split("=");

				if (url.length == 2) {
					if ("photo".equals(url[0])) {
						this.setImageUrl(url[1]);
					} else if ("audio".equals(url[0])) {
						this.setAudioUrl(url[1]);
					}
				}
			}
		}

		String alarmControls = surveyDetail.getControlParameter1();

		String keyValues[] = alarmControls.split("\\|");

		Date date = null;

		String startDate = null;
		for (String para : keyValues) {

			String keyValue[] = para.split("=");
			if (keyValue.length != 2) {
				continue;
			}
			String key = keyValue[0].trim();
			String value = keyValue[1].trim();

			if ("StartDate".equals(key)) {

				startDate = value;

			} else if ("StartTime".equals(key)) {
				startTimeStr = value;

			} else if ("EndDate".equals(key)) {

				try {

					date = dateFormatter.parse(value);
					this.setEnd(date.getTime());
				} catch (ParseException e) {

					e.printStackTrace();
				}

			} else if ("UpperLimit".equals(key)) {
				this.setUpperLimit(value);

			} else if ("LowerLimit".equals(key)) {
				this.setLowerLimit(value);

			} else if ("Buttons".equals(key)) {
				this.setButtons(value);
			}

			else if ("Active".equals(key)) {

				this.setActive(Helper.toBoolean(value));

			} else if ("Message".equals(key)) {

				this.setMessage(value);

			} else if ("Repeat".equals(key)) {

				String[] repeats = value.split(",");
				for (String repeatCode : repeats) {
					AlarmRepeatPojo repeat = AlarmRepeatPojo.getAlarmRepeat(Helper.toInt(repeatCode));
					if (repeat != AlarmRepeatPojo.NO_REPEAT)
						this.getRepeats().add(repeat);
				}

			}

		}
		try {
			String start = startTimeStr;
			if (startTimeStr.startsWith("Now+")) {
				start = startTimeStr.split("\\+")[1].trim();
				withRespectToCurrentTime = true;
			}

			if (withRespectToCurrentTime) {
				triggerTime = System.currentTimeMillis() + Helper.stringTimeToMillis(start);
			}
			date = dateTimeFormatter.parse(startDate + " " + start);
			this.setStart(date.getTime());
		} catch (ParseException e) {

			e.printStackTrace();
		}

	}

	public long calculateWrtInstallTime() {

		boolean isWrt = false;
		long time = 0;
		String start = startTimeStr;
		if (startTimeStr.startsWith("Now+")) {
			start = startTimeStr.split("\\+")[1].trim();
			isWrt = true;
		}

		if (isWrt) {
			time = installTime + Helper.stringTimeToMillis(start);
		}
		return time;

	}

	public void triggerTImeWithRespectToCurrentTIme() {
		String start = startTimeStr;
		if (startTimeStr.startsWith("Now+")) {
			start = startTimeStr.split("\\+")[1].trim();
			withRespectToCurrentTime = true;
		}

		if (withRespectToCurrentTime) {
			triggerTime = System.currentTimeMillis() + Helper.stringTimeToMillis(start);
		}

	}

	public String getButtons() {
		return buttons;
	}

	public void setButtons(String buttons) {
		this.buttons = buttons;
	}

	public Long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public boolean isValidAlarm() {
		boolean isActive = true;
		long currentTime = System.currentTimeMillis();

		isActive = this.active;
		if (!active) {
			isActive = false;
		} else

		if (this.repeats.size() == 0) {
			if (this.start < currentTime) {
				isActive = false;
			}
		} else {
			if (this.end < currentTime) {
				isActive = false;
			}
		}

		if (startTimeStr.startsWith("Now+")) {
			isActive = true;
		}

		return isActive;
	}

	public String getRepeatText() {
		StringBuilder strRepeats = new StringBuilder();
		for (AlarmRepeatPojo repeat : repeats) {
			strRepeats.append(repeat.getText()).append(" ");
		}
		return strRepeats.toString();
	}

	public String getRepeatString() {
		StringBuilder strRepeats = new StringBuilder();
		int size = repeats.size();
		for (int i = 0; i < size; i++) {
			strRepeats.append(repeats.get(i).getRepeatType());
			if (i < size - 1) {
				strRepeats.append(",");
			}
		}

		return strRepeats.toString();
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return message + " | " + startTimeStr;
	}

	public long getSurveyId() {
		return surveyId;
	}

	public void setSurveyId(long surveyId) {
		this.surveyId = surveyId;
	}

	public String getSurveyKey() {
		return surveyKey;
	}

	public void setSurveyKey(String surveyKey) {
		this.surveyKey = surveyKey;
	}

	public long getStart() {
		return start;
	}

	public void setStart(long start) {
		this.start = start;
	}

	public long getEnd() {
		return end;
	}

	public void setEnd(long end) {
		this.end = end;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<AlarmRepeatPojo> getRepeats() {
		return repeats;
	}

	public void setRepeats(List<AlarmRepeatPojo> repeats) {
		this.repeats = repeats;
	}

	public void setRepeats(String repeatsStr) {
		String[] repeats = repeatsStr.split(",");
		for (String repeatStr : repeats) {
			repeatStr = repeatStr.trim();

			if (repeatStr.length() > 0) {
				AlarmRepeatPojo alarmRepeatPojo = AlarmRepeatPojo.getAlarmRepeat(Integer.parseInt(repeatStr));
				this.repeats.add(alarmRepeatPojo);
			}

		}

	}

	public String getImageUrl() {
		return imageUrl;
	}

	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}

	public long getSequanceNo() {
		return sequanceNo;
	}

	public void setSequanceNo(long sequanceNo) {
		this.sequanceNo = sequanceNo;
	}

	public String getUpperLimit() {
		return upperLimit;
	}

	public void setUpperLimit(String upperLimit) {
		this.upperLimit = upperLimit;
	}

	public String getLowerLimit() {
		return lowerLimit;
	}

	public void setLowerLimit(String lowerLimit) {
		this.lowerLimit = lowerLimit;
	}

	public int getPendingIntentId() {
		return pendingIntentId;
	}

	public void setPendingIntentId(int pendingIntentId) {
		this.pendingIntentId = pendingIntentId;
	}

	public int getRepeatType() {
		return repeatType;
	}

	public void setRepeatType(int repeatType) {
		this.repeatType = repeatType;
	}

	public boolean isRepeat() {
		return repeat;
	}

	public void setRepeat(boolean repeat) {
		this.repeat = repeat;
	}

	public long getTriggerTime() {
		return triggerTime;
	}

	public void setTriggerTime(long triggerTime) {
		this.triggerTime = triggerTime;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public boolean isWithRespectToCurrentTime() {
		return withRespectToCurrentTime;
	}

	public void setWithRespectToCurrentTime(boolean withRespectToCurrentTime) {
		this.withRespectToCurrentTime = withRespectToCurrentTime;
	}

	public String getStartTimeStr() {
		return startTimeStr;
	}

	public void setStartTimeStr(String startTimeStr) {
		this.startTimeStr = startTimeStr;
	}

	public String getAudioUrl() {
		return audioUrl;
	}

	public void setAudioUrl(String audioUrl) {
		this.audioUrl = audioUrl;
	}

	public long getInstallTime() {
		return installTime;
	}

	public void setInstallTime(long installTime) {
		this.installTime = installTime;
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {

		dest.writeLong(start);
		dest.writeLong(end);
		dest.writeInt(active == true ? 1 : 0);
		dest.writeLong(this.sequanceNo);
		dest.writeString(buttons);
		dest.writeInt(pendingIntentId);
		dest.writeInt(repeatType);
		dest.writeLong(id);
		dest.writeLong(triggerTime);
		dest.writeString(message);
		dest.writeByte((byte) (repeat == true ? 1 : 0));
		dest.writeString(imageUrl);
		dest.writeString(upperLimit);
		dest.writeString(lowerLimit);
		dest.writeLong(surveyId);
		dest.writeInt(withRespectToCurrentTime == true ? 1 : 0);
		dest.writeString(audioUrl);
		dest.writeString(startTimeStr);
		dest.writeLong(installTime);

		dest.writeTypedList(this.repeats);

	}

	public AlarmPojo(Parcel in) {

		this.start = in.readLong();
		this.end = in.readLong();
		this.active = in.readInt() == 1;
		this.sequanceNo = in.readLong();
		this.buttons = in.readString();
		this.pendingIntentId = in.readInt();
		this.repeatType = in.readInt();
		this.id = in.readLong();
		this.triggerTime = in.readLong();
		this.message = in.readString();
		this.repeat = in.readByte() == 1;
		this.imageUrl = in.readString();
		this.upperLimit = in.readString();
		this.lowerLimit = in.readString();
		this.surveyId = in.readLong();
		this.withRespectToCurrentTime = in.readInt() == 1;
		this.audioUrl = in.readString();
		this.startTimeStr = in.readString();
		this.installTime = in.readLong();

		in.readTypedList(this.repeats, AlarmRepeatPojo.CREATOR);
	}

	public static final Parcelable.Creator<AlarmPojo> CREATOR = new Parcelable.Creator<AlarmPojo>() {
		public AlarmPojo createFromParcel(Parcel in) {
			return new AlarmPojo(in);
		}

		public AlarmPojo[] newArray(int size) {
			return new AlarmPojo[size];
		}
	};

	// public boolean equals(Object o) {
	// if (null == o || !(o instanceof AlarmPojo)) {
	// return false;
	// }
	//
	// return ((AlarmPojo) o).getId().longValue() == this.id;
	//
	// }
	//
	// public int hashCode() {
	//
	// return id.hashCode();
	//
	// };

	public static void commit(AlarmPojo alarm, Context ctx) {
		String address = null;
		AlarmTable alarmTable = new AlarmTable(ctx);

		alarmTable.insertRow(alarm);

		address = alarm.getImageUrl();
		if (null != address) {
			try {

				if (!new File(Helper.getTempFile(Helper.getHashNameFromUrl(address) + "")).exists())
					Helper.downloadFile(address, Helper.getTempFile(Helper.getHashNameFromUrl(address) + ""));
			} catch (Exception ex) {
				Log.e(SurveyPojo.class.getSimpleName(), "Alarm Image Download Error: " + ex.getMessage() + ":"
						+ address);
			}
		}

		address = alarm.getAudioUrl();
		if (null != address) {
			try {

				if (!new File(Helper.getTempFile(Helper.getHashNameFromUrl(address) + "")).exists())
					Helper.downloadFile(address, Helper.getTempFile(Helper.getHashNameFromUrl(address) + ""));
			} catch (Exception ex) {
				Log.e(SurveyPojo.class.getSimpleName(), "Alarm Audio Download Error: " + ex.getMessage() + ":"
						+ address);
			}
		}

		alarmTable.closeDB();
	}

	public static void commit(List<AlarmPojo> alarms, long surveyId, Context ctx) {
		String address = null;
		AlarmTable alarmTable = new AlarmTable(ctx);
		for (AlarmPojo alarm : alarms) {

			alarm.setSurveyId(surveyId);
			alarmTable.insertRow(alarm);

			address = alarm.getImageUrl();
			if (null != address) {
				try {

					if (!new File(Helper.getTempFile(Helper.getHashNameFromUrl(address) + "")).exists())
						Helper.downloadFile(address, Helper.getTempFile(Helper.getHashNameFromUrl(address) + ""));
				} catch (Exception ex) {
					Log.e(SurveyPojo.class.getSimpleName(), "Alarm Image Download Error: " + ex.getMessage() + ":"
							+ address);
				}
			}

			address = alarm.getAudioUrl();
			if (null != address) {
				try {

					if (!new File(Helper.getTempFile(Helper.getHashNameFromUrl(address) + "")).exists())
						Helper.downloadFile(address, Helper.getTempFile(Helper.getHashNameFromUrl(address) + ""));
				} catch (Exception ex) {
					Log.e(SurveyPojo.class.getSimpleName(), "Alarm Audio Download Error: " + ex.getMessage() + ":"
							+ address);
				}
			}

		}

		alarmTable.closeDB();
	}

}
